
import Vue from 'vue'
import VueRouter from "vue-router";
Vue.use(VueRouter);
import Login from '@/views/Login'
import store from "../store/index";
import {get} from "@/util/axios";
import Home from '@/views/Home'

const router  = new VueRouter({
    routes: [
        {
            path: '/',
            name:'Home',
            component: Home
        },
        {
            path: '/login',
            name: 'Login',
            component: Login
        }
    ]
})


/**
 * 路由导航
 * to: 将要去哪个页面
 * from: 从哪个页面过来
 * next: 放行到哪个页面
 */
router.beforeEach((to, from, next) => {
    // 获取token
    const token = sessionStorage.getItem('token');
    if (!token) {
        if (to.path === '/login') {
            next();
        } else {
            next(`/login?redirect=${to.fullPath}`);
        }
    } else {
        get('/user/getUserInfo').then(res=>{
            const user = res.data;
            store.commit('setUser', user);
        })
        // 已经登录
        if (to.path === '/login') {
            next('/');
        } else {
            next();
        }
    }
});

export default router
